<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/10
 * Time: 22:29
 */
namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

class Shipping extends Api
{
	
	protected $noNeedRight = ['*'];
	//电商ID
	const EBusinessID = '1334121';
//	const EBusinessID = 'test1334121';
	
	//电商加密私钥，快递鸟提供，注意保管，不要泄漏
	const AppKey = '7c7f95cc-cec7-4ab2-a68f-97108bc77990';
//	const AppKey = 'a0429f42-d892-435a-bf66-6d3190595d11';
	//请求url
	const ReqURL = 'http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
	
	/**
	 * Json方式 查询订单物流轨迹
	 */
	
	public function info()
	{
		$code = input('post.code');
		$no = input('post.no');
		
		if(!$code || !$no){
			$this->error('参数错误');
		}
		
		
		$requestData = "{'OrderCode':'','ShipperCode':'" . $code . "','LogisticCode':'" . $no . "'}";
		$datas = array(
			'EBusinessID' => self::EBusinessID,
			'RequestType' => '1002',
			'RequestData' => urlencode($requestData),
			'DataType' => '2',
		);
		$datas['DataSign'] = $this->encrypt($requestData, self::AppKey);
		$result = $this->sendPost(self::ReqURL, $datas);
		$result = \GuzzleHttp\json_decode($result, true);
		$traces = [];
		$tips = '查询成功';
		if($result['Success']){
			$traces = array_reverse($result['Traces']);
		} else{
			$tips = $result['Reason'];
		}
		//根据公司业务处理返回的信息......
		$returnData = [
			'traces' => $traces,
			'tips' => $tips
		];
		$this->success('查询成功', $returnData);
	}
	
	/**
	 *  post提交数据
	 * @param  string $url 请求Url
	 * @param  array $datas 提交的数据
	 * @return url响应返回的html
	 */
	public function sendPost($url, $datas)
	{
		$temps = array();
		foreach ($datas as $key => $value) {
			$temps[] = sprintf('%s=%s', $key, $value);
		}
		$post_data = implode('&', $temps);
		$url_info = parse_url($url);
		if (empty($url_info['port'])) {
			$url_info['port'] = 80;
		}
		$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
		$httpheader .= "Host:" . $url_info['host'] . "\r\n";
		$httpheader .= "Content-Type:application/x-www-form-urlencoded;charset=utf-8\r\n";
		$httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
		$httpheader .= "Connection:close\r\n\r\n";
		$httpheader .= $post_data;
		$fd = fsockopen($url_info['host'], $url_info['port']);
		fwrite($fd, $httpheader);
		$gets = "";
		$headerFlag = true;
		while (!feof($fd)) {
			if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
				break;
			}
		}
		while (!feof($fd)) {
			$gets .= fread($fd, 128);
		}
		fclose($fd);
		
		return $gets;
	}
	
	/**
	 * 电商Sign签名生成
	 * @param data //内容
	 * @return DataSign 签名
	 */
	public function encrypt($data)
	{
		return urlencode(base64_encode(md5($data . self::AppKey)));
	}
	
	/**
	 * 生成订单
	 */
	public function send(){
		header('Content-type:text/html;charset=utf8');
		$data = cache('order');
//		dump($data);
		echo $data['PrintTemplate'];
		die;
		//构造电子面单提交信息
		$eorder = [];
		$eorder["ShipperCode"] = "SF"; //快递公司编号
		$eorder["OrderCode"] = time();//订单号
		$eorder["PayType"] = 1; //邮费支付方式:1-现付，2-到付，3-月结，4-第三方支付
		$eorder["ExpType"] = 1; //快递类型：1-标准快件
		
		$sender = [];
		$sender["Name"] = "李先生"; //发件人
		$sender["Mobile"] = "18888888888"; //电话与手机，必填一个
		$sender["ProvinceName"] = "李先生"; //发件省（如广东省，不要缺少“省”）
		$sender["CityName"] = "深圳市"; //发件市（如深圳市，不要缺少“市”）
		$sender["ExpAreaName"] = "福田区"; //发件区（如福田区，不要缺少“区”或“县”）
		$sender["Address"] = "赛格广场5401AB"; //发件人详细地址
		
		$receiver = [];
		$receiver["Name"] = "李先生";//收件人
		$receiver["Mobile"] = "18888888888";//电话与手机，必填一个
		$receiver["ProvinceName"] = "李先生";//收件省（如广东省，不要缺少“省”）
		$receiver["CityName"] = "深圳市"; //收件市（如深圳市，不要缺少“市”）
		$receiver["ExpAreaName"] = "福田区"; //	收件区（如福田区，不要缺少“区”或“县”）
		$receiver["Address"] = "赛格广场5401AB";//收件人详细地址
		
		$commodityOne = [];
		$commodityOne["GoodsName"] = "其他";//商品名称
		$commodity = [];
		$commodity[] = $commodityOne;
		
		$eorder["Sender"] = $sender;
		$eorder["Receiver"] = $receiver;
		$eorder["Commodity"] = $commodity;
		$eorder['IsReturnPrintTemplate'] = 1; //返回电子面单模板：0-不需要；1-需要


//调用电子面单
		$jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);

//$jsonParam = JSON($eorder);//兼容php5.2（含）以下
		
//		echo "电子面单接口提交内容：<br/>".$jsonParam;
		$jsonResult = $this->submitEOrder($jsonParam);
//		echo "<br/><br/>电子面单提交结果:<br/>".$jsonResult;

//解析电子面单返回结果
		
		$result = json_decode($jsonResult, true);
		cache('order',$result);
		dump($result);
		die;
		echo "<br/><br/>返回码:".$result["ResultCode"];
		if($result["ResultCode"] == "100") {
			echo "<br/>是否成功:".$result["Success"];
		}
		else {
			echo "<br/>电子面单下单失败";
		}
	}
	
	/**
	 * 取消订单接口
	 */
	public function cancelOrder(){
		$url = 'http://api.kdniao.cc/api/EOrderService';
		$requestData = [
			'ShipperCode' => 'SF', //物流公司编号
			'OrderCode' => '1527211400', //订单号
			'ExpNo' => '620230952292', //物流单号
		];
		$requestData = json_encode($requestData);
		$datas = array(
			'EBusinessID' => self::EBusinessID,
			'RequestType' => '1147',
			'RequestData' => urlencode($requestData) ,
			'DataType' => 2,
		);
		$datas['DataSign'] = $this->encrypt($requestData);
		$result=$this->sendPost($url, $datas);
		dump($result);
	}
	
	
	/**
	 * Json方式 调用电子面单接口
	 */
	public function submitEOrder($requestData){
//		$url = 'http://sandboxapi.kdniao.cc:8080/kdniaosandbox/gateway/exterfaceInvoke.json';
		$url = 'http://api.kdniao.cc/api/Eorderservice';
		$datas = array(
			'EBusinessID' => self::EBusinessID,
			'RequestType' => '1007',
			'RequestData' => urlencode($requestData) ,
			'DataType' => '2',
		);
		$datas['DataSign'] = $this->encrypt($requestData);
		$result=$this->sendPost($url, $datas);
		
		//根据公司业务处理返回的信息......
		
		return $result;
	}
	
	public function shippingList(){
		$list = Db::name('shipping')->order(['sort' => 'ASC'])->field('id, name')->select();
		$this->success('查询成功', $list);
	}
}